import re
import time
from flask import request
from flask_restful import abort
from flask_login import current_user, login_user
from funcy import project
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import IntegrityError
from funcy import partial

from redash import models, limiter
from redash.permissions import (
    require_admin,
)
from redash.handlers.base import (
    BaseResource,
    require_fields,
    get_object_or_404,
    paginate,
    order_results as _order_results,
)

from redash.authentication.account import (
    invite_link_for_user,
    send_invite_email,
    send_password_reset_email,
    send_verify_email,
)
from redash.settings import parse_boolean
from redash import settings



class TabletypeNewResource(BaseResource):
    def get(self):
        result = models.Tabletype.get_id()
        return result[0]

    @require_admin
    def post(self):
        req = request.get_json(force=True)
        require_fields(req, ("code","name"))

        tabletype = models.Tabletype(
        code=req["code"],
        type=req["type"],
        org=self.current_org,
        name = req["name"],
        numauto=req["numauto"],
        numhand = req["numhand"],
        numhead=req["numhead"],
        numdate = req["numdate"],
        numfoot=req["numfoot"],
        footlenth = req["footlenth"],
        )
        try:
            models.db.session.add(tabletype)
            models.db.session.commit()
        except IntegrityError as e:
            if "code" in str(e):
                abort(400, message="编号已存在.")
            abort(500)

        # timeserial.record_event(
        #     {"action": "create", "object_id": timeserial.id, "object_type": "timeserial"}
        # )

class TabletypeResource(BaseResource):
    def get(self, tabletype_id):
        result = models.Tabletype.get_by_id(tabletype_id)
        return result.to_dict()

    @require_admin
    def post(self, tabletype_id):
        req = request.get_json(force=True)
        require_fields(req, ("code","name"))

        tabletype = models.Tabletype.get_by_id(tabletype_id)
        params = dict(code=req["code"], type=req["type"], name=req["name"],numauto=req["numauto"], numhand = req["numhand"],
                      numhead=req["numhead"], numdate = req["numdate"],numfoot=req["numfoot"], footlenth = req["footlenth"])

        try:
            self.update_model(tabletype, params)
            models.db.session.commit()
        except IntegrityError as e:
            if "name" in str(e):
                abort(400, message="名称已存在.")
            abort(500)

    @require_admin
    def delete(self, tabletype_id):
        tabletype =  models.Tabletype.get_by_id(tabletype_id)
        models.db.session.delete(tabletype)
        models.db.session.commit()

class TabletypeListResource(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        page = req["page"]
        page_size = req["pagesize"]
        name = req["name"]
        code = req["code"]
        strwhere ="t1.org_id=" +str(self.current_org.id)
        if name !='' :
            strwhere = strwhere + " and t1.name like '%"+name+"%'"
        if code !='' :
            strwhere = strwhere + " and t1.code = '"+code+"'"
        strgetfield ="""  t1.*"""

        tblname = """ public.tabletype t1  """
        orderfield ="t1.id"
        result = models.ContractApply.get_pagequery(tblname,strgetfield,orderfield,page_size,page,0,strwhere)
        return result[0]
